package com.example.demo;

import com.example.demo.common.TimeTransfer;
import com.example.demo.common.TimerCount;
import com.example.demo.dao.UserMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Task;
import com.example.demo.model.UserInfo;
import com.example.demo.service.SendMailService;
import com.example.demo.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;
@Slf4j
@SpringBootApplication
public class DemoApplication {


	public static void main(String[] args) {
		ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
		TaskService bean = run.getBean(TaskService.class);
		SendMailService bean2 = run.getBean(SendMailService.class);
		UserMapper bean3 = run.getBean(UserMapper.class);
		// 1.项目启动时：初始化数据表（如果没有就创建，有就啥也不做）
		bean.createTaskTable();
		bean.createUserTable();
		// 2.项目启动时获取数据库中所有未完成的任务，加入定时队列（已超时直接更新为true，未超时则加入定时器）
		List<Task> allTodoTask = bean.getAllTodoTask();
		for (Task todoTask : allTodoTask) {
			long lastTime = TimeTransfer.convertTimeToNumber(todoTask.getDate());
			long currentLine = TimeTransfer.convertTimeToNumber(System.currentTimeMillis());
			long delay = lastTime - currentLine;
			log.warn("[DemoApplication]需要等待时间为："+delay);

			Date deadLine = new Date(lastTime);
			if (delay <= 0) {
				log.warn("[DemoApplication]超时");
				bean.updateTask(todoTask.getId());
			} else {
				// 获取到用户对象
				UserInfo user = bean3.getUserById(todoTask.getUserId());
				if (user == null) {
					log.error("[addTask] 查询到用户为空！userid = "+todoTask.getId());
					throw new ApplicationException("用户对象为空");
				}
				// 发送邮件的定时任务
				Date sendMailTime = new Date(lastTime-30000);
				TimerCount.timer.schedule(new TimerTask() {
					@Override
					public void run() {
						// 加上这个条件是为了防止中途被修改
						Task taskByName = bean.getTaskByName(todoTask.getName(), todoTask.getUserId());
						if (taskByName != null && !taskByName.getDeleteState() && taskByName.getIsDone() == 0) {
							bean2.sendMail(user.getEmail(),"任务截止提醒",
									"您的任务：【"+todoTask.getName()+"】即将截止了，请尽快完成。详情请咨询：http://118.25.26.147:37080/login.html");
							log.info("[DemoApplication]提醒邮件已发送：userName = "+user.getUsername()+", taskName = "+todoTask.getName());
						}
					}
				}, sendMailTime);


				TimerCount.timer.schedule(new TimerTask() {
					@Override
					public void run() {
						// 这里是定时结束后需要执行的任务
						// 获取任务ID
						Integer taskId = todoTask.getId();
						// 更新为超时状态
						Task taskByName = bean.getTaskByName(todoTask.getName(), todoTask.getUserId());
						if (taskByName != null && taskByName.getIsDone()==0) {
							bean.updateTask(taskId);
							log.warn("[DemoApplication]您的任务已超时 userName = "+user.getUsername()+", taskName = "+todoTask.getName());
						}
					}
				},deadLine);
			}
		}

	}


}
